import { MyHead } from "../../../components/head"
import { Steps, Form, Input, Picker, Space, Button, DatePickerRef, DatePicker, Toast, Tag, ImageUploader, TextArea, ImageUploadItem } from "antd-mobile"
import {
    CheckCircleFill,
} from 'antd-mobile-icons'

import { PickerValue } from "antd-mobile/es/components/picker-view"
import { RefObject, useRef, useState ,useEffect} from "react"
import dayjs from 'dayjs'
import { changeImg } from "../../../api/user"
import { useDispatch, useSelector } from "react-redux"
import { AppDispatch, MsdataTypes, RootReducer, } from "../../../types/store"
import { changeBu, changeMSData, clearData } from "../../../rtk/reduers/data"
import { addMainShi } from "../../../api/AddMs"
import { useTiaoZhuan } from "../../../hooks/routers"
const { Step } = Steps
const AddMs = () => {
    // const [current, setcurrent] = useState(0)
    const [form] = Form.useForm();
    const [value, setValue] = useState<PickerValue[]>([])
    const [visible, setVisible] = useState(false)
    const [fileList, setFileList] = useState<ImageUploadItem[]>([
    ])
    const {Tz} = useTiaoZhuan()
    const userData = useSelector<RootReducer,foundUserType|null>(state=>state.MyData.userData)
    const MSData = useSelector<RootReducer, MsdataTypes>(state => state.MyData.MSData)
    const buzhou = useSelector<RootReducer, number>(state => state.MyData.buzhou)
    const uploadFileRef = useRef<HTMLInputElement>(null)
    // 保存视频
    const [audiosData, setAduiosData] = useState<File>()
    // 保存图片
    const [imgData, setImgData] = useState<File[]>([])
    // 上传视频音频
    const chufa = () => {
        uploadFileRef.current!.click()
    }
    // 总结数据
    const [testData, settestData] = useState<string>()
    const uploadFileData = async () => {
        setAduiosData(uploadFileRef.current!.files![0])
        console.log(audiosData);

    }

    const dispatch: AppDispatch = useDispatch();
    const maxCount = 9; //最大九个

    // 点击上一步
    const lastStep = () => {
        // setcurrent(current - 1);
        dispatch(changeBu(buzhou - 1))
    }
    // 点击删除图片
    const DeleteOneImg = (item: any) => {
        console.log(item)
    }

    // 点击添加图片
    async function mockUpload(file: File) {
        imgData.push(file)
        console.log('kkkk');
        
        setImgData([...imgData])
        // await changeImg(data)
        return {
            url: URL.createObjectURL(file),
        }
    }
    // 点击下一步
    const nextStep = () => {
        // console.log(form.getFieldsValue());

        if (buzhou == 0) {
            form.validateFields()
                .then(res => {
                    console.log(res)
                    dispatch(changeMSData({...res,date1:res.date}))
                    dispatch(changeBu(buzhou + 1))
                })
                .catch(err => {
                    console.log(err)
                    Toast.show({
                        content: "表单校验失败"
                    })
                })
        } else if (buzhou == 1) {
            console.log(tages, imgData);

            if (tages.length > 0 && imgData.length > 0) {
                dispatch(changeBu(buzhou + 1))
                dispatch(changeMSData({
                    audioSrc1: audiosData,
                    imgs1: imgData,
                    tags: tages}
                ))
            } else {
                Toast.show({
                    content: "数据不正确"
                })
            }
        }
    }
    // 添加标签
    const [tages, setTagData] = useState<{ label: string, value: string, id: number }[]>([])
    const tagAdd = (item: { label: string, value: string, id: number }) => {
        console.log(item);
        if (tages.length == 6) {
            Toast.show({
                content: "最多只能选中六个"
            })
        } else {
            tages.push(item)
            let y = [...tages]
            let x = MianTagList.filter(i => item.id != i.id);
            setMain(x)
            setTagData(y)
        }
    }
    // 提交
    const tijiao = async () => {
        // 提交前将imgs的数据清空
        if(!userData || !localStorage.getItem('token')){
            Tz('/login')
            return
        }
        dispatch(changeMSData({ content: testData ,imgs:[]}))
        let imgDatas = MSData.imgs1;
        for (let i = 0; i < MSData.imgs1.length; i++) {
            let data = new FormData();
            data.append('file', imgDatas[i]);
            let res = await changeImg(data)
            dispatch(changeMSData({imgs:[...MSData.imgs,res.path]}))
        }
        dispatch(changeMSData({imgs1:[]}))
        if (MSData.audioSrc) {
            let data = new FormData();
            data.append('file', MSData.audioSrc1!)
            let res = await changeImg(data)
            dispatch(changeMSData({ audioSrc:res.path,audioSrc1:''}))
        }
        console.log(MSData);
        let re = await addMainShi(MSData)

        if(re.code == 200){
            Tz('/wdms')
            dispatch(changeBu(0))
            dispatch(clearData())
        }
    }
    const deleTages = (item: { label: string, value: string, id: number }) => {
        let y = tages.filter(ites => ites.id != item.id);
        setTagData(y)
        MianTagList.push(item)
        setMain([...MianTagList.sort((a, b) => a.id - b.id)])
    }
    const data = [
        {
            title: "第一步",
            msg: '添加面试基本信息'
        },
        {
            title: "第二步",
            msg: "添加面试记录信息"
        },
        {
            title: '第三步',
            msg: "添加面试总结"
        }
    ]
    const LevelTypes = [
        [
            { label: '简单', value: 1 },
            { label: '复杂', value: 2 },
            { label: '困难', value: 3 },
            { label: '地狱', value: 4 },
            { label: '无解', value: 5 },
        ]
    ]
    const [MianTagList, setMain] = useState([
        {
            label: "Vue2",
            value: 'vue2',
            id: 1
        },
        {
            label: "React",
            value: 'react',
            id: 2
        },
        {
            label: "jQuery",
            value: 'jq',
            id: 3
        },
        {
            label: "Css3",
            value: 'css',
            id: 4
        }, {
            label: "HTML5",
            value: 'HTML5',
            id: 5
        }, {
            label: "ES6",
            value: 'es6',
            id: 6
        }, {
            label: "JS",
            value: 'js',
            id: 7
        }, {
            label: "Webpack",
            value: 'webpack',
            id: 8
        }, {
            label: "Node",
            value: 'node',
            id: 9
        }, {
            label: "Ts",
            value: 'ts',
            id: 10
        }, {
            label: "Git",
            value: 'git',
            id: 11
        }, {
            label: "小程序",
            value: '小程序',
            id: 12
        }, {
            label: "Ajax",
            value: 'Ajax',
            id: 13
        }, {
            label: "适配",
            value: '适配',
            id: 14
        }, {
            label: "Vue3",
            value: 'Vue3',
            id: 15
        }, {
            label: "地图",
            value: '地图',
            id: 16
        }, {
            label: "数据库",
            value: '数据库',
            id: 17
        }, {
            label: "大屏/大数据",
            value: '大屏/大数据',
            id: 18
        }, {
            label: "低代码",
            value: '低代码',
            id: 19
        }, {
            label: "微前端",
            value: '微前端',
            id: 20
        }, {
            label: "微服务",
            value: '微服务',
            id: 21
        }, {
            label: "混合App",
            value: '混合App',
            id: 22
        }, {
            label: "Http",
            value: 'Http',
            id: 23
        }, {
            label: "UniApp",
            value: 'UniApp',
            id: 24
        },
        {
            label: "其他",
            value: '其他',
            id: 25
        },
    ])
    useEffect(()=>{
        // 获取初始地址
        form.setFieldValue('address',MSData.address);
        // 获取初始名称
        form.setFieldValue('campany',MSData.campany);
        // 获取初始等级
        form.setFieldValue('level',MSData.level);
        // 获取初始标签
        setTagData([...MSData.tags]) 
        // 获取初始图片
        if(MSData.imgs1.length>0){
            let imgYuan = MSData.imgs1.map(item=> {return {url:URL.createObjectURL(item)}})
            setFileList(imgYuan)
            setImgData(MSData.imgs1)
        }
        
        // 如果存在时间就加载时间
        if(MSData.date1){
            form.setFieldValue('date',new Date(MSData.date1))
        }
        
        // 获取初始录音
        setAduiosData(MSData.audioSrc1)
        
    },[])
    return (
        <div>
            <MyHead title='添加面试' />
            <Steps
                direction='vertical'
                current={buzhou}
                style={{
                    '--title-font-size': '17px',
                    '--description-font-size': '15px',
                    '--indicator-margin-right': '12px',
                    '--icon-size': '22px',
                    paddingTop: 50
                }}
            >
                {
                    data.map(item => (
                        <Step
                            key={item.title}
                            title={item.title}
                            description={item.msg}
                            icon={<CheckCircleFill />}
                        />
                    ))
                }
            </Steps>
            <div style={{ padding: 10 }}>
                {buzhou == 0 && <Form
                    form={form}
                    style={{ padding: 1 }}
                    layout='vertical'
                >

                    <Form.Item
                        name='campany'
                        label='面试公司名称'
                        rules={[{ required: true, message: '必填项' }]}
                    >
                        <Input clearable  placeholder='请输入名称' />
                    </Form.Item>
                    <Form.Item
                        name='address'
                        label='面试地址'
                        rules={[{ required: true, message: '必填项' }]}
                    >
                        <Input clearable placeholder='请输入地址' />
                    </Form.Item>
                    <Form.Item
                        name='level'
                        label='面试难度'
                        rules={[{ required: true, message: '必填项' }]}
                        onClick={() => {
                            setVisible(true)
                        }}>
                        <Picker
                            columns={LevelTypes}
                            value={value}
                            visible={visible}
                            onConfirm={(v) => {
                                console.log(v);
                                form.setFieldValue('level', v)
                                setValue(v)
                                setVisible(false)

                            }}
                            onCancel={() => {
                                setVisible(false)
                            }}
                        >
                            {(items) => {
                                return (
                                    <Space align='center'>
                                        {items.every(item => item === null)
                                            ? '未选择'
                                            : items.map(item => item?.label ?? '未选择').join(' - ')}
                                    </Space>
                                )
                            }}
                        </Picker>
                    </Form.Item>
                    <Form.Item
                        name='date'
                        label='面试时间'
                        trigger='onConfirm'
                        rules={[{ required: true, message: '必填项' }]}
                        onClick={(e, datePickerRef: RefObject<DatePickerRef>) => {
                            datePickerRef.current?.open()
                        }}
                    >
                        <DatePicker
                            precision='minute'>
                            {value =>value ? dayjs(value).format('YYYY-MM-DD HH:mm') : '请选择日期'}
                        </DatePicker>
                    </Form.Item>
                </Form>
                }
                {buzhou == 1 && <div>
                    <div className="label" style={{ fontSize: 16 }}>
                        面试标签
                        <span style={{ fontSize: 10 }}>(最多6个)</span>
                    </div>
                    <div style={{ display: 'flex', flexWrap: 'wrap' }}>
                        {
                            tages.map((item, index) => (
                                <Tag className="mt10 mr10 " style={{ padding: 5 }} color='warning' key={index} onClick={() => deleTages(item)} >
                                    {item.label}
                                </Tag>
                            ))
                        }
                    </div>
                    可选择的标签:
                    <div className="tag-list" style={{ display: 'flex', flexWrap: 'wrap' }}>
                        {
                            MianTagList.map((item, index) => {
                                return (
                                    <Tag className="mt10 mr10 " style={{ padding: 5 }} color='#2db7f5' key={index} onClick={() => tagAdd(item)} >
                                        {item.label}
                                    </Tag>
                                )
                            })
                        }
                    </div>
                    <div className="label" style={{ fontSize: 16, marginTop: 15 }}>
                        面试图片
                        <span style={{ fontSize: 10 }}>(最多9个)</span>
                    </div>
                    <div style={{ marginTop: 15 }}>
                        <ImageUploader
                            value={fileList}
                            onChange={setFileList}
                            upload={mockUpload}

                            multiple
                            maxCount={9}
                            showUpload={fileList.length < maxCount}

                            onDelete={
                                DeleteOneImg
                            }
                        />
                    </div>
                    <div className="label" style={{ fontSize: 16, marginTop: 15 }}>
                        面试录音
                        <span style={{ fontSize: 10 }}>(可不传)</span>
                    </div>

                    <div>
                        <Button color="primary" onClick={chufa} size="mini">上传录音</Button>
                        <input type="file" onChange={uploadFileData} style={{ display: 'none' }} ref={uploadFileRef} />
                    </div>
                    {
                        audiosData && <audio src={URL.createObjectURL(audiosData)} controls ></audio>
                    }
                </div>
                }
                {
                    buzhou == 2 &&
                    <div>
                        <div className="label" style={{ fontSize: 16, marginTop: 15 }}>
                            面试总结
                            <span style={{ fontSize: 10 }}>(记录面试题目)</span>
                        </div>
                        <TextArea
                            className='mt10'
                            style={{ border: '1px solid #ddd', borderRadius: 10, padding: 5 }}
                            placeholder='请输入'
                            showCount
                            maxLength={400}
                            rows={12}
                            value={testData}
                            onChange={settestData}
                        />
                    </div>
                }
                <div style={{ display: 'flex', justifyContent: "space-around" }}>

                    {
                        buzhou != 0 && <Button block color="warning" onClick={lastStep}>上一步</Button>
                    }
                    {
                        buzhou != data.length - 1 && <Button block color="primary" onClick={nextStep}>下一步</Button>
                    }
                    {
                        buzhou == data.length - 1 && <Button block color="success" onClick={tijiao}>提交</Button>
                    }
                </div>

            </div>
        </div>
    )
}

export default AddMs